package com.zhichat.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean("redisTemplateString")
    public RedisTemplate<String, Object> redisTemplateString(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerialize = jackson2JsonRedisSerialize();
        redisTemplate.setKeySerializer(stringSerializer); //key序列化方式
        redisTemplate.setValueSerializer(jackson2JsonRedisSerialize); //value序列化方式
        redisTemplate.setHashKeySerializer(stringSerializer); //hash key序列化方式
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerialize); //hash value序列化方式
        redisTemplate.afterPropertiesSet(); //设置序列化后，必须调用该方法
        return redisTemplate;
    }

    private Jackson2JsonRedisSerializer jackson2JsonRedisSerialize() {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //指定要序列化的类型，然后我们的对象就可以直接序列化
        ObjectMapper om = new ObjectMapper(); //创建jackson对象
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); //开启默认的类型信息
        jackson2JsonRedisSerializer.setObjectMapper(om); //设置转换器
        return jackson2JsonRedisSerializer;
    }
}
